<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
	<title id="title">修德抄经堂</title>
	<link rel="stylesheet" type="text/css" href="../bower_components/mui/dist/css/mui.css">
	<link rel="stylesheet" type="text/css" href="../css/base.css">
	<link rel="stylesheet" type="text/css" href="../css/full.css">
	<link rel="stylesheet" type="text/css" href="../css/yinshuaye.css">
	<script src="../bower_components/mui/dist/js/mui.min.js"></script>
	<script src="../bower_components/jquery/dist/jquery.js"></script>
	<script src="../js/common.js"></script>
</head>

<body>
	<div id="mcover1">
		<div>
			<div id="xian">
				<p>经书未收藏！</p>
				<button>确认</button>
			</div>
		</div>
	</div>
	<div class="page">
		<div class="content">

			<div id="main">
				<img id="sutraCover" class="shuming" />
				<!-- src="../img/bore/book.png"/> -->
				<div class="jieshao">
					<div class="bor_t_b" id="sutraName">
						<!-- <p class="same color ">《心经》王羲之行书线装本</p> -->
					</div>
					<div class="shuoming">
						<p class="p_l fang color" id="vowTime">
							<!-- 2017.04.05发愿 -->
						</p>
						<p class="p_r fang color" id="finishTime">
							<!-- 2017.05.05完成 -->
						</p>
					</div>
				</div>
				<div style="clear: both;"></div>
			</div>

			<div class="yinshua">
				<p id="yia" class="color same">印刷</p>
				<p id="neirong" class="color fang">
					<!--<span>金色</span>-->
					<!--<span>铜版纸</span>-->
					<!--<span>线装</span>-->
					<span class="right">本</span>
					<input style="font-size: 14px;" id="num" class="right fang" type="number" value="" placeholder="请输入数量" name="num">
				</p>
				<p id="jiage" class="color fang">￥
					<span id="tongji">0.00</span>元
					<a href="yinshuashuoming.html">
						<img src="../img/gantan.png" />
					</a>
				</p>
			</div>

			<div class="peisong">
				<p id="peis" class="color same">配送</p>
				<div id="deliverAddressList">
					<!-- <p class="color fang dizhi">
						<span class="right">本</span>
						<input style="font-size: 14px;" id="num_peis" class="right fang" type="number" value="" placeholder="请输入数量" name="num">
						<span>
							<i id="name">张三</i>
							<i id="phone">18296191996</i>
						</span>
						<br/>
						<span id="address">北京市海淀区中关村创业大街</span>
					</p>
 -->
				</div>

				<div class="newAddress"></div>

				<a href="dizhi.html">
					<p class="tianjia fang">
						<img src="../img/benxin/tianjia.png">
						<span>选择配送地址</span>
					</p>
				</a>
			</div>
			<button type="submit" id="fanhui" class="fang">提交</button>
			</a>
		</div>
	</div>
</body>
<script>
	function formatTime(timeStr) {
		if (!timeStr) {
			return "未";
		}

		var date = parseISODate(timeStr);
		return date.getFullYear() + "." + (date.getMonth() + 1) + "." + date.getDate()
	}

	function genAddressPrintNumID(address_id) {
		return "addressPrintNum_" + address_id;
	}

	function genDonationPrintNumID(address_id) {
		return "donationPrintNum_" + address_id;
	}

	function changePrice(userTranscriptionID, num) {
		var csrftoken = getCookie('csrftoken');
		$.ajax({
			url: '/fe/print/user_transcription/' + userTranscriptionID + '/price_calculate',
			method: "POST",
			beforeSend: function (xhr, settings) {
				xhr.setRequestHeader("X-CSRFToken", csrftoken);
			},
			data: {
				"user_transcription_id": userTranscriptionID,
				"print_num": num,
			},
			success: function (data) {
				$('#tongji').text(data.data.total_price);
			},
		});
	}

	// 页面从其他页面返回时，输入框中的数字仍然存在，故需要调用初始化函数获取总金额更新到页面
	function initPrice(userTranscriptionID) {
		var num = $("#num").val();
		if (num > 0) {
			changePrice(userTranscriptionID, num)
		}
	}

	function loadSelectedAddressList() {
		var addressList = JSON.parse(localStorage.getItem("selectedAddressList"))
		var html = "";

		for (var i = 0; i < addressList.length; i++) {
			var address = addressList[i];

			html +=
				'<p class="color fang dizhi">' +
					'<span class="right">本</span>';

			if(address.type == "address") {
				html +=
					'<input style="font-size: 14px;" id="' + genAddressPrintNumID(address.id) + '" class="right fang" type="number" value="" placeholder="请输入数量" name="num">' +
					'<span>' +
						'<i id="name">' + address.contact + '</i>' +
						'<i id="phone">' + address.phone + '</i>' +
					'</span>' +
					'<br/>' +
					'<span id="address">' + address.address + '</span>';
			} else if (address.type == "donation"){
				html +=
					'<input style="font-size: 14px;" id="' + genDonationPrintNumID(address.id) + '" class="right fang" type="number" value="" placeholder="请输入数量" name="num">' +
					'<span>' +
						'<i id="name">' + address.name+ '</i>' +
					'</span>' +
					'<br/>';
					// '</span>';
			}
			html += '</p>';
		}
		$("#deliverAddressList").html(html);
	}

	function loadDefaultAddress() {
		$.ajax({
			url: "/fe/user/address_list",
			success: function (data) {
				var addressList = data.data;

				if (addressList.length == 0) {
					return;
				}

				// 遍历所有地址，获取默认地址，如果没有则使用第一个
				var defaultAddress = addressList[0];
				for (var i = 1; i < addressList.length; i++) {
					var address = addressList[i];
					if (address.is_default) {
						defaultAddress = address;
					}
				}

				// 写入localStorage
				defaultAddress.type = "address";
				localStorage.setItem("selectedAddressList", JSON.stringify([defaultAddress]))

				// 更新页面显示
				$("#deliverAddressList").html(
					'<p class="color fang dizhi">' +
						'<span class="right">本</span>' +
						'<input style="font-size: 14px;" id="' + genAddressPrintNumID(defaultAddress.id) + '" class="right fang" type="number" value="" placeholder="请输入数量" name="num">' +
						'<span>' +
							'<i id="name">' + defaultAddress.contact + '</i>' +
							'<i id="phone">' + defaultAddress.phone + '</i>' +
						'</span>' +
						'<br/>' +
						'<span id="address">' + defaultAddress.address + '</span>' +
					'</p>'
				);
			},
		});
	}

	$(function (data) {
		// function allPrice(id, price) {
		// 	var num = parseInt(id.val());
		// 	console.log(num)
		// 	$('#tongji').text(num * price);
		// }
		// var vid = localStorage.getItem('versionId');

		var userTranscriptionID = localStorage.getItem('userTranscriptionID');
		var csrftoken = getCookie('csrftoken');

		initPrice(userTranscriptionID);

		if (localStorage.getItem("selectedAddressList")) {
			// 有已选择的，则恢复显示
			loadSelectedAddressList();
		} else {
			// 没有已选择的，则加载默认地址
			loadDefaultAddress();
		}

		$.ajax({
			url: '/fe/print/user_transcription/' + userTranscriptionID + '/config',
			success: function (data) {
			    if (data.status == '200'){
                    var sutraInfo = data.data.sutra_info;
                    var transcriptionInfo = data.data.transcription_info;

                    // 设定封面图
                    $("#sutraCover").attr("src", sutraInfo.cover_url);
                    // 设定名称
                    $("#sutraName").html(
                        '<p class="same color ">' + sutraInfo.name + '</p>'
                    )
                    // 设定时间
                    $("#vowTime").text(formatTime(transcriptionInfo.vow_time) + "发愿")
                    $("#finishTime").text(formatTime(transcriptionInfo.finish_time) + "完成")


                    // 设定印刷信息
                    var html = '<span class="type">' + transcriptionInfo.font_color + '</span>' +
                        '<span class="type">' + transcriptionInfo.material_name + '</span>' +
                        '<span class="type">' + transcriptionInfo.book_binding + '</span>';
                    $('#neirong').append(html);

                    $("#num").change(function () {
                        var num = $(this).val();
                        if (num == "") {
                            alert("请输入正确的数量");
                        } else {
                            changePrice(userTranscriptionID, num);
                            // allPrice($('#num'), price);
                            //                            if(1<=num && num<50){
                            //
                            //                                //alert(50)
                            //                            }
                            //                            if(51<=num && num<100){
                            //                                qian = num*45.00;
                            //                                $("#tongji").text(qian);
                            //                                //alert(45)
                            //                            }
                            //                            if(101<=num && num<500){
                            //                                qian = num*40.00;
                            //                                $("#tongji").text(qian);
                            //                                //alert(40)
                            //                            }
                            //                            if(500<=num){
                            //                                qian = num*30.00;
                            //                                $("#tongji").text(qian);
                            //                                //alert(30)
                            //                            }
                        }
                    })
				}
				else {
                    $("#mcover1").css("display","block");
				}
			}
		});
        $("#xian button").click(function () {
            history.back();
        })
		$('#fanhui').click(function (e) {
			e.preventDefault();

			// 验证
			var totalPrintNum = parseInt($("#num").val());
			var totalInputPrintNum = 0;
			if (totalPrintNum == 0){
				alert("请填写配送数");
				return
			}

			// 从localStorage中获取已选择地址及数量
			var addressList = JSON.parse(localStorage.getItem("selectedAddressList"));
			for (var i = 0; i < addressList.length; i++ ) {

				var address = addressList[i];
				if (address.type == "address") {
					var inputID = genAddressPrintNumID(address.id);
				} else if (address.type == "donation") {
					var inputID = genDonationPrintNumID(address.id);
				} else {
					alert("数据错误");
					return;
				}

				var printNum = parseInt($("#" + inputID).val());
				if(printNum == 0){
					alert("请输入数量");
					return;
				}

				address.num = printNum;
				totalInputPrintNum += printNum;
			}

			if(totalInputPrintNum != totalPrintNum) {
				alert('配送数与印刷数不符合');
				return;
			}

			// 更新localStorage(印刷数)
			localStorage.setItem("selectedAddressList", JSON.stringify(addressList));
			// 跳转
			location.href = 'peisong.html';
		})
	})

	mui('body').on('tap', 'a', function () {
		document.location.href = this.href;
	});
	$("body").css({
		'overflow': 'scroll'
	});


	//
	//		$("#num_peis").change(function(){
	//			var reg = /^\+?[1-9]\d*$/;
	//			var num = parseInt($(this).val());
	//			reg.test(num)
	//			if(reg.test(num)){
	//				return;
	//			}else{
	//				if($(this).val() ==""){
	//					return;
	//				}else{
	//					alert("请输入正确的数量");
	//					$(this).val("");
	//				}
	//			}
	//		});

	//		mui('body').on('tap','.dizhi',function(){
	//			window.location.href='./dizhi.html';
	//		});


	//		if(window.location.href.indexOf('?')>-1){
	//			var parm=parseURL(window.location.href);
	//			var html=['<p class="color fang dizhi">',
	//						'<span class="right">本</span>',
	//						'<input style="font-size: 14px;" id="num_peis" class="right fang" type="text" value="" placeholder="请输入数量" name="num">',
	//						// '<span>张三</span>',
	//						// '<span>18296191996</span><br/>',
	//						'<span>'+decodeURI(parm.add)+'</span><br/>',
	//						'<span>'+decodeURI(parm.det)+'</span>',
	//					  '</p>'].join('');
	//			$(".newAddress").append(html);
	//		}
</script>

</html>